package com.kakarote.crm9.erp.ding.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiProcessinstanceCreateRequest;
import com.dingtalk.api.response.OapiProcessinstanceCreateResponse;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Redis;
import com.kakarote.crm9.erp.admin.entity.AdminRole;
import com.kakarote.crm9.erp.admin.entity.AdminUser;
import com.kakarote.crm9.erp.admin.entity.AdminUserRole;
import com.kakarote.crm9.erp.admin.service.AdminRoleService;
import com.kakarote.crm9.erp.admin.service.AdminUserService;
import com.kakarote.crm9.erp.ding.entity.*;
import com.kakarote.crm9.erp.ding.service.*;
import com.kakarote.crm9.utils.*;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Clear
public class DingController extends Controller {
    @Inject
    private DingConfigService dingConfigService;
    @Inject
    private DingAllUserService dingAllUserService;
    @Inject
    private DingLoginService dingLoginService;
    @Inject
    private AdminRoleService adminRoleService;
    @Inject
    private AdminUserService adminUserService;
    @Inject
    private AppidService appidService;
    @Inject
    private DingTokenService dingTokenService;
    @Inject
    private WxLoginService wxLoginService;
    @Inject
    private DingRuService dingRuService;


    public void get(){
        renderJson(dingConfigService.get());
    }

    public void getUser()throws Exception {
        DingConfig dingConfig = dingConfigService.getConfig();
        String accss = AuthHelper.getAccessToken(dingConfig.getAppKey(),dingConfig.getAppSecret());
        Integer offset = 0; Integer size = 20;
        while (true) {
            Map<String, Object> parms = new HashMap<String, Object>();
            parms.put("status_list", "-1");
            parms.put("offset", offset);
            parms.put("size", size);
            JSONObject jsonObject = JSONObject.fromObject(parms);
            HttpUtils httpUtils = new HttpUtils();
            String result = httpUtils.post("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob?access_token=" + accss, jsonObject.toString());
            JSONObject ress = JSONObject.fromObject(result).getJSONObject("result");
            List<String> ss = ress.getJSONArray("data_list");
            for (int i = 0; i < ss.size(); i++) {
                DingAlluser dingAlluser = new DingAlluser();
                dingAlluser.setUserId(ss.get(i));
                dingAlluser.setStatic("无状态");
                Integer sd = dingAllUserService.getSum(ss.get(i));
                if (dingAllUserService.getSum(ss.get(i))==0) {
                    dingAlluser.save();
                }
            }
            if (!ress.containsKey("next_cursor")) {
                break;
            }
            offset = ress.getInt("next_cursor");
            size = 20;

        }
//        System.out.println("SS="+ss);
    }
    public void getUserDetailed()throws Exception {
        DingConfig dingConfig = dingConfigService.getConfig();
        String accss = AuthHelper.getAccessToken(dingConfig.getAppKey(),dingConfig.getAppSecret());
        List<DingAlluser> list = dingAllUserService.getAll();
        if(list.size()>0) {
            for (DingAlluser dingAlluser : list) {
                if (dingAlluser.getName() == null & dingAlluser.getMobile() == null) {
//                if (dingAlluser.getUnionid() == null) {
                    Map<String, String> parms = new HashMap<String, String>();
                    parms.put("userid", dingAlluser.getUserId());
                    HttpUtils httpUtils = new HttpUtils();
                    String result = httpUtils.doGet("https://oapi.dingtalk.com/user/get?access_token=" + accss, parms, null);
                    JSONObject resu = JSONObject.fromObject(result);
                    if (resu.getString("errcode").equals("0")) {
                        dingAlluser.setName(resu.getString("name"));
                        dingAlluser.setMobile(resu.getString("mobile"));
                        if (resu.containsKey("position")) {
                            dingAlluser.setPosition(resu.getString("position"));
                        }
                        if (resu.containsKey("jobnumber")) {
                            dingAlluser.setJobnumber(resu.getString("jobnumber"));
                        }
                        if (resu.containsKey("unionid")) {
                            dingAlluser.setUnionid(resu.getString("unionid"));
                        }
                        dingAllUserService.upAll(dingAlluser);
                    }
                }

            }
        }
    }

    public DingConfig getQian() throws Exception{
        DingConfig dingConfig = new DingConfig();
        Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        String stringToSign = milliSecond.toString();
        dingConfig.setAppKey(stringToSign);
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec("Nlk2l18cZZdO5XDOGXyBmiHSn-Ad_C1F-C5bncW-CqUPKODvTvUtAhOmOPj6pSYV".getBytes("UTF-8"), "HmacSHA256"));
        byte[] signatureBytes = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String signature = new String(Base64.encodeBase64(signatureBytes));
        String urlEncodeSignature = multipleUtil.urlEncode(signature,"utf-8");
        dingConfig.setAppSecret(urlEncodeSignature);
//        JSONObject sd = JSONObject.fromObject(signature);
//        renderJson(signature);
        return dingConfig;

    }
    /**处理钉钉授权码信息*/
    public void codetoLogin(String code) throws Exception{
        String accessKey= "dingoahdwfojjd9iwfhirf";
        Map<String, Object> parms = new HashMap<String, Object>();
        parms.put("tmp_auth_code", code);
        JSONObject jsonObject = JSONObject.fromObject(parms);
        DingConfig dingConfig = getQian();
        String url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey="+accessKey+"&timestamp="+dingConfig.getAppKey()+"&signature="+dingConfig.getAppSecret();
        HttpUtils httpUtils = new HttpUtils();
        String result = httpUtils.post(url,jsonObject.toString());
        JSONObject resu = JSONObject.fromObject(result);
        JSONObject sd = resu.getJSONObject("user_info");
        DingLogin dingLogin = new DingLogin();
        if(sd.containsKey("nick")){
            dingLogin.setNick(sd.getString("nick"));
        }
        if(sd.containsKey("dingId")){
            dingLogin.setDingId(sd.getString("dingId"));
        }
        if(sd.containsKey("openid")){
            dingLogin.setOpenid(sd.getString("openid"));
        }
        if(sd.containsKey("unionid")){
            dingLogin.setUnionid(sd.getString("unionid"));
        }
        dingLogin.setStatic("1");
        dingLogin.setLoginTime(new Date());
        if(sd.containsKey("openid")) {
            if (dingLoginService.findOpenid(sd.getString("openid")) == 0) {
                dingLogin.save();
            }
        }
        DingAlluser dingAlluser = AuthHelper.getUser(AuthHelper.getUserid(sd.getString("unionid")));
        AdminUser user = new AdminUser();
        if(dingAlluser.getMobile()!=null) {
            if (dingAllUserService.findMobiles(dingAlluser.getMobile()) == 0) {
                if(sd.containsKey("nick")) {
                    user.setUsername(sd.getString("nick"));
                    user.setRealname(sd.getString("nick"));
                }
                user.setPassword("123456");
                user.setMobile(dingAlluser.getMobile());
                String salt = IdUtil.fastSimpleUUID();
                user.setNum(RandomUtil.randomNumbers(15));
                user.setSalt(salt);
                user.setPassword(BaseUtil.sign((user.getUsername().trim() + user.getPassword().trim()), salt));
                user.setCreateTime(new Date());
                user.save();
                AdminUserRole adminUserRole = new AdminUserRole();
                adminUserRole.setRoleId(3);
                adminUserRole.setUserId(user.getUserId());
                adminUserRole.save();
            }
            user = adminUserService.MtoUser(dingAlluser.getMobile());
            getAuser(user);
        }else {
            renderJson(R.error("您不是本企业用户或信息有误，联系管理员处理！"));
        }
    }

    /** 钉钉扫码登录*/
    public void getDingUser (String loginTmpCode,String gotos) throws Exception{
        String accessKey= "dingoahdwfojjd9iwfhirf";
        String url1 = "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoahdwfojjd9iwfhirf&response_type=code&scope=snsapi_login&redirect_uri="+gotos+"&loginTmpCode="+loginTmpCode;
        String eurl = multipleUtil.getRedirectUrl(url1);
        String code = getParamByUrl(eurl,"code");
        codetoLogin(code);
//        Map<String, Object> parms = new HashMap<String, Object>();
//        parms.put("tmp_auth_code", code);
//        JSONObject jsonObject = JSONObject.fromObject(parms);
//        DingConfig dingConfig = getQian();
//        String url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey="+accessKey+"&timestamp="+dingConfig.getAppKey()+"&signature="+dingConfig.getAppSecret();
//        HttpUtils httpUtils = new HttpUtils();
//        String result = httpUtils.post(url,jsonObject.toString());
//        JSONObject resu = JSONObject.fromObject(result);
//        JSONObject sd = resu.getJSONObject("user_info");
//        DingLogin dingLogin = new DingLogin();
//        if(sd.containsKey("nick")){
//            dingLogin.setNick(sd.getString("nick"));
//        }
//        if(sd.containsKey("dingId")){
//            dingLogin.setDingId(sd.getString("dingId"));
//        }
//        if(sd.containsKey("openid")){
//            dingLogin.setOpenid(sd.getString("openid"));
//        }
//        if(sd.containsKey("unionid")){
//            dingLogin.setUnionid(sd.getString("unionid"));
//        }
//        dingLogin.setStatic("1");
//        dingLogin.setLoginTime(new Date());
//        if(sd.containsKey("openid")) {
//            if (dingLoginService.findOpenid(sd.getString("openid")) == 0) {
//                dingLogin.save();
//            }
//        }

//        DingAlluser dingAlluser = dingAllUserService.getUnionid(sd.getString("unionid"));

//        DingAlluser dingAlluser = AuthHelper.getUser(AuthHelper.getUserid(sd.getString("unionid")));
//        AdminUser user = new AdminUser();
//        if(dingAlluser.getMobile()!=null) {
//            if (dingAllUserService.findMobiles(dingAlluser.getMobile()) == 0) {
//                if(sd.containsKey("nick")) {
//                    user.setUsername(sd.getString("nick"));
//                    user.setRealname(sd.getString("nick"));
//                }
//                user.setPassword("123456");
//                user.setMobile(dingAlluser.getMobile());
//                String salt = IdUtil.fastSimpleUUID();
//                user.setNum(RandomUtil.randomNumbers(15));
//                user.setSalt(salt);
//                user.setPassword(BaseUtil.sign((user.getUsername().trim() + user.getPassword().trim()), salt));
//                user.setCreateTime(new Date());
//                user.save();
//                AdminUserRole adminUserRole = new AdminUserRole();
//                adminUserRole.setRoleId(3);
//                adminUserRole.setUserId(user.getUserId());
//                adminUserRole.save();
//            }
//            user = adminUserService.MtoUser(dingAlluser.getMobile());
//            if(user.getStatus()!=null) {
//                if (user.getStatus() == 2) {
//                    user.setStatus(1);
//                }
//                String token = IdUtil.simpleUUID();
//                user.setLastLoginIp(BaseUtil.getLoginAddress(getRequest()));
//                user.setLastLoginTime(new Date());
//                user.update();
//                user.setRoles(adminRoleService.queryRoleIdsByUserId(user.getUserId()));
//                Redis.use().setex(token, 360000, user);
//                setCookie("Admin-Token", token, 360000);
//                renderJson(R.ok().put("Admin-Token", token).put("user", user).put("auth", adminRoleService.auth(user.getUserId())));
//            }
//        }else {
//            renderJson(R.error("您不是本企业用户或信息有误，联系管理员处理！"));
//        }
    }
    /** 钉钉账号登录*/
    public void DingLogin (String code) throws Exception{
        String codes = code;
        codetoLogin(code);
    }
    /** 微信开放平台重组url*/
    public void getWXurl (){
        AppId appId = appidService.get("1");
        String nonce =getRandom(10);
        String sign_type="md5";
        String timestamp = String.valueOf(new Date().getTime()).substring(0,10);
        Map<String, Object> json1 = new HashMap<>();
        Map<String, Object> json2 = new HashMap<>();
        json1.put("policy_no","21900188888888");
        json2.put("redirect_url","http://2a433746q0.wicp.vip/workbench/index");
        json2.put("user_type","1");
        json2.put("first_regist","N");
        json2.put("attach",json1);
        JSONObject js2 = JSONObject.fromObject(json2);
        String adds = appId.getAppId()+js2.toString()+nonce+appId.getSecretKey()+sign_type+timestamp;
        String encodeStr = DigestUtils.md5Hex(appId.getAppId()+js2.toString()+nonce+appId.getSecretKey()+sign_type+timestamp);
        String ssd =encodeStr;
        String urld = "https://kong-int.ihxlife.com/api/v2/uc/user/login/index?app_id="+appId.getAppId()+"&nonce="+nonce+"&timestamp="+timestamp+"&sign_type="+sign_type+"&sign="+encodeStr+"&data="+js2.toString();
        renderJson(R.ok().put("url",urld));
    }

    public void wxlogin(String token){
        String tk = token;
        HttpUtils httpUtils = new HttpUtils();
        Map<String,String> head = new HashMap<>();
        DingToken dingToken = dingTokenService.get("1");
        head.put("Content-Type","application/json");
        head.put("Authorization",dingToken.getAccessToken());
        head.put("serial_no","1190"+getRandom(10));
        String url = "https://kong-int.ihxlife.com/api/v2/uc/user/query";
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        String result = httpUtils.doGet(url,map,head);
        JSONObject da = JSONObject.fromObject(result).getJSONObject("data");
        AdminUser user = new AdminUser();
        WxLogin wxLogin = new WxLogin();
        if(da.containsKey("user_id")){
           wxLogin.setUserId(da.getString("user_id"));
        }
        if(da.containsKey("mobile")){
            wxLogin.setMobile(da.getString("mobile"));
        }
        if(da.containsKey("openid")){
            wxLogin.setOpenId(da.getString("openid"));
        }
        if(da.containsKey("agent_code")){
            wxLogin.setAgentCode(da.getString("agent_code"));
        }
        if(da.containsKey("name")){
            wxLogin.setName(da.getString("name"));
        }
        if(da.containsKey("sex")){
            wxLogin.setSex(da.getString("sex"));
        }
        if(da.containsKey("birthday")){
            wxLogin.setBirthday(da.getString("birthday"));
        }
        if(da.containsKey("id_type")){
            wxLogin.setIdType(da.getString("id_type"));
        }
        wxLogin.setCreateDate(new Date());
        if(wxLoginService.getWsum(da.getString("mobile"))==0){
            wxLogin.save();
        }
        if(adminUserService.getMsum(da.getString("mobile"))==0){
            user.setUsername(da.getString("name"));
            user.setRealname(da.getString("name"));
            user.setPassword("123456");
            user.setMobile(da.getString("mobile"));
            String salt = IdUtil.fastSimpleUUID();
            user.setNum(RandomUtil.randomNumbers(15));
            user.setSalt(salt);
            user.setPassword(BaseUtil.sign((user.getUsername().trim() + user.getPassword().trim()), salt));
            user.setCreateTime(new Date());
            user.save();
            AdminUserRole adminUserRole = new AdminUserRole();
            adminUserRole.setRoleId(3);
            adminUserRole.setUserId(user.getUserId());
            adminUserRole.save();
        }
        user = adminUserService.MtoUser(da.getString("mobile"));
        getAuser(user);
    }

    /** 根据用户信息生成对应规则 */
    public void getAuser(AdminUser user){
        if(user.getStatus()!=null) {
            if (user.getStatus() == 2) {
                user.setStatus(1);
            }
            String tokens = IdUtil.simpleUUID();
            user.setLastLoginIp(BaseUtil.getLoginAddress(getRequest()));
            user.setLastLoginTime(new Date());
            user.update();
            user.setRoles(adminRoleService.queryRoleIdsByUserId(user.getUserId()));
            Redis.use().setex(tokens, 360000, user);
            setCookie("Admin-Token", tokens, 360000);
            renderJson(R.ok().put("Admin-Token", tokens).put("user", user).put("auth", adminRoleService.auth(user.getUserId())));
        }
    }
    /** 根据位数生成随机数 */
    public static String getRandom(int length){
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }
    /** 获取网址中特定参数的值 */
    private static String getParamByUrl(String url, String name) {
        url += "&";
        String pattern = "(\\?|&){1}#{0,1}" + name + "=[a-zA-Z0-9]*(&{1})";

        Pattern r = Pattern.compile(pattern);

        Matcher m = r.matcher(url);
        if (m.find( )) {
            System.out.println(m.group(0));
            return m.group(0).split("=")[1].replace("&", "");
        } else {
            return null;
        }
    }

    public void doGet()
            throws ServletException, IOException {
        HttpServletRequest request=getRequest();
        HttpServletResponse response = getResponse();

        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        PrintWriter out = response.getWriter();

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            System.out.print("echostr=" + echostr);
            out.print(echostr);
        }

        out.flush();
        out.close();
        out = null;
    }

    protected void doPost()
            throws ServletException, IOException {
        HttpServletRequest req=getRequest();
        HttpServletResponse resp = getResponse();

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        try {
            Map<String,String> map = MessageUtil.xmlToMap(req);
            String toUserName = map.get("ToUserName");
            String fromUserName = map.get("FromUserName");
            String msgType = map.get("MsgType");
            String content = map.get("Content");
            //判断请求是否事件类型 event
            if(MessageUtil.MESSAGE_EVENT.equals(msgType)){
                String eventType = map.get("Event");
                //若是关注事件  subscribe
                if(MessageUtil.EVENT_SUB.equals(eventType)){
                    String mycontent = MessageUtil.menuText();
                    String message = MessageUtil.initText(toUserName, fromUserName, mycontent);
                    out.print(message);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            out.close();
        }

    }
    public void sendshen() throws Exception{
        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
        OapiProcessinstanceCreateRequest request = new OapiProcessinstanceCreateRequest();
        request.setAgentId(264537852L);
        request.setProcessCode("PROC-EF600B0F-6D3A-4A41-9169-426CDC027795");
// 审批流表单参数，设置各表单项值
        List<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValues = new ArrayList<OapiProcessinstanceCreateRequest.FormComponentValueVo>();

// 单行输入框
        OapiProcessinstanceCreateRequest.FormComponentValueVo vo1 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        vo1.setName("外貌");
        vo1.setValue("一般");

// 多行输入框
        OapiProcessinstanceCreateRequest.FormComponentValueVo vo2 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        vo2.setName("其他");
        vo2.setValue("2");

        OapiProcessinstanceCreateRequest.FormComponentValueVo vo3 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        vo3.setName("关联组件");
        String ss = "[\"bc73ea22-db4c-4d6c-b661-15a2f350e14f\"]";
        vo3.setValue(JSON.toJSONString(Arrays.asList(Arrays.asList(ss))));

// 图片
//        OapiProcessinstanceCreateRequest.FormComponentValueVo vo3 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//        vo3.setName("图片示例");
//        vo3.setValue("[\"http://xxxxx\"]");

// 明细包含控件
// 明细-单行输入框
//        OapiProcessinstanceCreateRequest.FormComponentValueVo ItemName1 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//        ItemName1.setName("明细-单行输入框示例");
//        ItemName1.setValue("明细-单行输入框value");
//// 明细-多行输入框
//        OapiProcessinstanceCreateRequest.FormComponentValueVo ItemName2 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//        ItemName2.setName("明细-多行输入框示例");
//        ItemName2.setValue("明细-多行输入框value");
//// 明细-照片
//        OapiProcessinstanceCreateRequest.FormComponentValueVo ItemName3 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//        ItemName3.setName("明细-图片示例");
//        ItemName3.setValue("[\"http://xxxxx\"]");
//
//// 明细
//        OapiProcessinstanceCreateRequest.FormComponentValueVo vo4 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//        vo4.setName("明细示例");
//        vo4.setValue(JSON.toJSONString(Arrays.asList(Arrays.asList(ItemName1, ItemName2, ItemName3))));
//
//// 附件
//        OapiProcessinstanceCreateRequest.FormComponentValueVo attachmentComponent = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//        JSONObject attachmentJson = new JSONObject();
//        attachmentJson.put("fileId", "6433971140");
//        attachmentJson.put("fileName", "2644.JPG");
//        attachmentJson.put("fileType", "jpg");
//        attachmentJson.put("spaceId", "1635477658");
//        attachmentJson.put("fileSize", "333");

//        JSONArray array = new JSONArray();
//        array.add(attachmentJson);
//        attachmentComponent.setValue(array.toJSONString());
//        attachmentComponent.setName("附件");

// 添加单行输入框、多行输入框、图片、明细、附件到表单
        formComponentValues.add(vo1);
        formComponentValues.add(vo2);
        formComponentValues.add(vo3);
//        formComponentValues.add(vo4);
//        formComponentValues.add(attachmentComponent);

        request.setFormComponentValues(formComponentValues);
        request.setApprovers("034940603436629681");
        request.setOriginatorUserId("034940603436629681");
        request.setDeptId(110926330L);
//        request.setCcList("034940603436629681");
        request.setCcPosition("START_FINISH");
        DingConfig dingConfig = dingConfigService.getConfig();
        String accessToken = AuthHelper.getAccessToken(dingConfig.getAppKey(),dingConfig.getAppSecret());
        OapiProcessinstanceCreateResponse response = client.execute(request,accessToken);
    }
    public void sendsh(String name,String sex,String school,String mobile) throws Exception{
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> map1 = new HashMap<>();
        Map<String,Object> map2 = new HashMap<>();
        Map<String,Object> map3 = new HashMap<>();
        Map<String,Object> map4 = new HashMap<>();
        Integer ssd = dingRuService.getSum(mobile);
        if(dingRuService.getSum(mobile)==0) {
            DingRu dingRu = new DingRu();
            dingRu.setName(name);
            dingRu.setSex(sex);
            dingRu.setSchool(school);
            dingRu.setMobile(mobile);
            dingRu.setCreateDate(new Date());
            dingRu.save();
        }
        List list = new ArrayList();
        map.put("agent_id","264537852");
        map.put("process_code","PROC-0712CB5E-8D10-4967-A08D-37D9D55F9246");
        map.put("originator_user_id","034940603436629681");
        map.put("dept_id","110926330");
//        map.put("approvers","034940603436629681");
        map1.put("name","姓名");
        map1.put("value",name);
        map2.put("name","性别");
        map2.put("value",sex);
        map3.put("name","学校");
        map3.put("value",school);
        map4.put("name","电话");
        map4.put("value",mobile);
        list.add(map1);list.add(map2);list.add(map3);list.add(map4);
        map.put("form_component_values",list);
        JSONObject jsonObject = JSONObject.fromObject(map);
        DingConfig dingConfig = dingConfigService.getConfig();
        String accessToken = AuthHelper.getAccessToken(dingConfig.getAppKey(),dingConfig.getAppSecret());
        String url = "https://oapi.dingtalk.com/topapi/processinstance/create?access_token="+accessToken;
        HttpUtils httpUtils = new HttpUtils();
        String result = httpUtils.post(url,jsonObject.toString());
        System.out.println(result);
        String ids = JSONObject.fromObject(result).getString("process_instance_id");
        DingRu dingRu = dingRuService.getRu(mobile);
        if(dingRuService.getSums(dingRu.getId())==0) {
            DingRuRoler dingRuRoler = new DingRuRoler();
            dingRuRoler.setRuId(dingRu.getId());
            dingRuRoler.setIdOne(ids);
            dingRuRoler.save();
        }
        renderJson(R.ok().put("ids",ids));
//        sendOne(ids);
    }
    public void sendOne(String ids,String wai,String pi,String shi,String bu)throws Exception {
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> map1 = new HashMap<>();
        Map<String,Object> map2 = new HashMap<>();
        Map<String,Object> map3 = new HashMap<>();
        Map<String,Object> map4 = new HashMap<>();
        ArrayList<String> strArray = new ArrayList<String> ();
        List list = new ArrayList();
        map.put("agent_id","264537852");
        map.put("process_code","PROC-EF600B0F-6D3A-4A41-9169-426CDC027795");
        map.put("originator_user_id","034940603436629681");
        map.put("dept_id","110926330");
//        map.put("approvers","034940603436629681");
        map1.put("name","外貌");
        map1.put("value",wai);
        map2.put("name","与岗位匹配度");
        map2.put("value",pi);
        map3.put("name","是否录用");
        map3.put("value",shi);
        map4.put("name","入职部门");
        map4.put("value",bu);
        list.add(map1);list.add(map2);list.add(map3);list.add(map4);
        map.put("form_component_values",list);
        JSONObject jsonObject = JSONObject.fromObject(map);
        DingConfig dingConfig = dingConfigService.getConfig();
        String accessToken = AuthHelper.getAccessToken(dingConfig.getAppKey(),dingConfig.getAppSecret());
        String url = "https://oapi.dingtalk.com/topapi/processinstance/create?access_token="+accessToken;
        HttpUtils httpUtils = new HttpUtils();
        String result = httpUtils.post(url,jsonObject.toString());
        String idss = JSONObject.fromObject(result).getString("process_instance_id");
        DingRuRoler dingRuRoler = dingRuService.getRuRoler(ids);
        dingRuRoler.setIdTwo(idss);
        dingRuRoler.update();
        renderJson(R.ok().put("ids",idss));
    }
    public void findHe(String idTwo) throws Exception{
        DingRuRoler dingRuRoler = dingRuService.getTwo(idTwo);
        String one = dingRuRoler.getIdOne();
        String two = dingRuRoler.getIdTwo();
        Map<String,String> map = getXiang(one);
        Map<String,String> map2 = getXiang(two);
        Map<String,String> map3 = new HashMap<String,String>();
        map3.putAll(map);map3.putAll(map2);
        DingRuAll dingRuAll = new DingRuAll();
        String mobile="";
        for(Map.Entry<String, String> entry : map3.entrySet()){
            if(entry.getKey().equals("姓名")){
                dingRuAll.setName(entry.getValue());
            }
            if(entry.getKey().equals("学校")){
                dingRuAll.setSchool(entry.getValue());
            }
            if(entry.getKey().equals("是否录用")){
                dingRuAll.setShi(entry.getValue());
            }
            if(entry.getKey().equals("与岗位匹配度")){
                dingRuAll.setPi(entry.getValue());
            }
            if(entry.getKey().equals("入职部门")){
                dingRuAll.setBu(entry.getValue());
            }
            if(entry.getKey().equals("外貌")){
                dingRuAll.setWai(entry.getValue());
            }
            if(entry.getKey().equals("性别")){
                dingRuAll.setSex(entry.getValue());
            }
            if(entry.getKey().equals("电话")){
                dingRuAll.setMobile(entry.getValue());
                mobile = entry.getValue();
            }
        }
        if(dingRuService.getAllsum(dingRuAll.getMobile())==0) {
            dingRuAll.setCreateDate(new Date());
            dingRuAll.save();
        }
        Integer ids =  dingRuService.getAll(mobile).getId();
        renderJson(R.ok().put("ids",ids));
    }
    public Map getXiang(String id) throws Exception{
        DingConfig dingConfig = dingConfigService.getConfig();
        String accessToken = AuthHelper.getAccessToken(dingConfig.getAppKey(),dingConfig.getAppSecret());
        String url = "https://oapi.dingtalk.com/topapi/processinstance/get?access_token="+accessToken;
        Map<String,Object> map = new HashMap<>();
        map.put("process_instance_id",id);
        com.alibaba.fastjson.JSONObject jj = HttpHelper.httpPost(url,map);
        com.alibaba.fastjson.JSONObject j1 = jj.getJSONObject("process_instance");
        JSONArray j2 = j1.getJSONArray("form_component_values");
        Map<String,String> map2 = new HashMap<>();
        if(j2.size()>0) {
            for (int i = 0; i < j2.size(); i++) {
                // 遍历 jsonarray 数组，把每一个对象转成 json 对象
//                JSONObject job = jone.getJSONObject(i);
                com.alibaba.fastjson.JSONObject job = j2.getJSONObject(i);
                map2.put(job.get("name").toString(),job.get("value").toString());
// 得到 每个对象中的属性值
                System.out.println(job.get("name") + "=" +(job.get("value")));
            }
        }
        return  map2;
    }
    public void getAlls(String ids){
        DingRuAll dingRuAll = dingRuService.getAlls(ids);
        renderJson(R.ok().put("dingRuAll",dingRuAll));
    }
}
